package org.itboys.shop.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.admin.entity.PostFeeDB;
import org.itboys.basetemplate.entity.VoucherUserMap;
import org.itboys.basetemplate.service.VoucherUserMapService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.CommonConstants.CONTENT_TYPE;
import org.itboys.commons.CommonConstants.DF;
import org.itboys.commons.CommonConstants.NUM;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.string.SelfStringUtils;
import org.itboys.commons.utils.tools.ResponseManager;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.product.dto.CommonTouristInfoDTO;
import org.itboys.product.dto.ReceiveAddressDTO;
import org.itboys.product.entity.CommonTouristInfo;
import org.itboys.product.entity.ReceiveAddress;
import org.itboys.product.service.CommonTouristInfoService;
import org.itboys.product.service.GoodsSourcePostFeeService;
import org.itboys.product.service.ReceiveAddressService;
import org.itboys.shop.dto.KVDto;
import org.itboys.shop.dto.order.WXOrderDetailDto;
import org.itboys.shop.dto.order.WXOrderItemDto;
import org.itboys.shop.dto.order.WXPreOrderDto_jd;
import org.itboys.shop.dto.order.WXPreOrderDto_ms;
import org.itboys.shop.dto.order.WXPreOrderDto_njl;
import org.itboys.shop.dto.order.WXToPayDto;
import org.itboys.shop.service.Manager.WXOrderManager;
import org.itboys.shop.tools.WXSession;
import org.itboys.trade.constant.OrderConstant;
import org.itboys.trade.entity.Cart;
import org.itboys.trade.entity.Comment;
import org.itboys.trade.entity.Order;
import org.itboys.trade.entity.OrderItem;
import org.itboys.trade.entity.Refund;
import org.itboys.trade.entity.TicketOrder;
import org.itboys.trade.entity.TicketOrderItem;
import org.itboys.trade.service.CartService;
import org.itboys.trade.service.CommentService;
import org.itboys.trade.service.OrderItemService;
import org.itboys.trade.service.OrderService;
import org.itboys.trade.service.RefundService;
import org.itboys.trade.service.TicketOrderItemService;
import org.itboys.trade.service.TicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 商品
 * @author 
 *
 */
@RestController
@RequestMapping("/wx/order")
public class WXOrderController extends BaseController{
	@Autowired
	private OrderService orderService;
	@Autowired
	private TicketOrderService ticketOrderService;
	@Autowired
	private CartService cartService;
	@Autowired
	private OrderItemService itemService;
	@Autowired
	private TicketOrderItemService ticketOrderItemService;
	@Autowired
	private WXOrderManager orderManager;
	@Autowired
	private CommentService commentService;
	@Autowired
	private ReceiveAddressService addressService;
	@Autowired
	private VoucherUserMapService voucherService;
	@Autowired
	private CommonTouristInfoService infoService;
	@Autowired
	private MemberService memberService; 
	@Autowired
	private RefundService refundService;
	@Autowired
	private GoodsSourcePostFeeService postFeeService;
	private static final String PRO_ORDER="normal";
	private static final String TICKET_ORDER="ticket";
	@RequestMapping("/prepareOrder")
	public ModelAndView prepareOrder(
			@RequestParam List<Long>cartIds,
			@Param("addressId") Long addressId,
			@Param("points")Integer points,
			@Param("voucherId")Long voucherId,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			Long memberId=WXSession.getMember(request).getId();
			ReceiveAddress address=null;
			if (null==addressId) {
				address=addressService.getMemberDefualtAddress(memberId);
			}else {
				address=addressService.getById(addressId);
			}
			List<Cart>carts=cartService.getByIds(cartIds);
			List<WXOrderItemDto>items=Lists.newArrayList();
			WXToPayDto payDto=new WXToPayDto();
			for (Cart c : carts) {
				payDto.add(orderManager.getPreItemDto( items, c,address.getCityId())); ;
			}
			WXOrderDetailDto dto=new WXOrderDetailDto();
			StringBuilder sb=new StringBuilder();
			for (Long id : cartIds) {
				if (null!=id) {
					sb.append(id).append(",");
				}
			}
			dto.setCartIds(sb.substring(0, sb.length()-1));
			
			dto.setItems(items);
			
			//此处获取默认地址
			if (null!=address) {
				dto.setAddressId(address.getId());
				dto.setToName(address.getName());
				dto.setToAddress(address.getAddress());
				dto.setToPhone(SelfStringUtils.mixMobile(address.getMobile()));
			}
			final Integer  totalFee=payDto.getTotalFee();
			dto.setTicketId(voucherId);
			List<VoucherUserMap>voucher=voucherService.getPayVoucherList(memberId,Double.valueOf(totalFee));
			List<KVDto>vouchers=voucher.stream().map(v->{
				KVDto kv=new KVDto(v.getId(), v.getName());
				if (null!=voucherId&&voucherId==v.getId()) {
					kv.setIsSelect(1);
					payDto.setTotalFee(totalFee-v.getMoney().intValue());
				}
				return kv;
			}).collect(Collectors.toList());
			if (null!=points) {
				payDto.setTotalFee(payDto.getTotalFee()-points);
			}
			payDto.setTotalFee(payDto.getTotalFee()+payDto.getExpressFee());
			dto.setExpressFee(NUM.DF_00.format(payDto.getExpressFee()/100d));
			dto.setTotalFee(NUM.DF_00.format(payDto.getTotalFee()/100d));
			model.addAttribute("preOrder", dto);
			model.addAttribute("vouchers", vouchers);
			return new ModelAndView("/order/ConfirmOrder");
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}
	@RequestMapping("/prepareOrder_ms")
	public ModelAndView prepareOrder_ms(
			@RequestParam Long proId,
			@RequestParam ("infoIds") List<Long>infoIds,
			@Param("start") String start,
			@Param("end") String end,
			@Param("num")Integer num,
			@Param("ticketId")Long voucherId,
			@Param("points")Integer points,
			@Param("name")String name,
			@Param("code")String mobile,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Long memberId=WXSession.getMember(request).getId();
		WXPreOrderDto_ms dto=null;
		List<CommonTouristInfoDTO> result=Lists.newArrayList();
		List<KVDto>vouchers=Lists.newArrayList();
		try {
			dto = orderManager.getPreOrder_ms(proId, infoIds, start, end, num, voucherId, points);
			result=getInfoList(infoIds, result);
			String total=getVouchers(voucherId, memberId, NUM.DF_00.parse(dto.getTotal()).doubleValue(), vouchers);
			dto.setTotal(total);
		} catch (ParseException e) {
			logger.error("",e);
		}
		dto.setBookName(name);
		dto.setMobile(mobile);
		model.addAttribute("vouchers", vouchers);
		model.addAttribute("list", result);
		model.addAttribute("preOrder", dto);
		return new ModelAndView("/order/ConfirmOrder_ms");
	}
	private String getVouchers(Long voucherId, Long memberId, Double total,List<KVDto> vouchers)
			throws ParseException {
		Double  totalFee=total ;//NUM.DF_00.parse(dto.getTotal()).doubleValue();
		List<VoucherUserMap>voucher=voucherService.getPayVoucherList(memberId,totalFee);
		for (VoucherUserMap v : voucher) {
			KVDto kv=new KVDto(v.getId(), v.getName());
			if (null!=voucherId&&voucherId==v.getId()) {
				kv.setIsSelect(1);
				totalFee=totalFee-v.getMoney();
			}
			vouchers.add(kv);
		}
		return NUM.DF_00.format(totalFee);
	}
	private List<CommonTouristInfoDTO> getInfoList(List<Long> infoIds, List<CommonTouristInfoDTO> result) {
		if (infoIds.size()>0) {
		Map<String, Object> param= Maps.newHashMap();
		infoIds.remove(null);
//		 param.put("memberId",memberId);
		 param.put("isDeleted in", new Integer[]{0,2});
		 param.put("id in", infoIds);
		 List<CommonTouristInfo> list = infoService.list(param);
		 for (CommonTouristInfo info : list) {
			 CommonTouristInfoDTO InfoDTO = new CommonTouristInfoDTO(info);
			 result.add(InfoDTO);
		 }
		 return result;
		}else {
			return Lists.newArrayList();
		}
	}
	@RequestMapping("/prepareOrder_njl")
	public ModelAndView prepareOrder_njl(
			@RequestParam Long proId,
			@RequestParam ("infoIds") List<Long>infoIds,
			@Param("start") String start,
			@Param("num")Integer num,
			@Param("voucherId")Long voucherId,
			@Param("points")Integer points,
			@Param("name")String name,
			@Param("mobile")String mobile,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Long memberId=WXSession.getMember(request).getId();
		WXPreOrderDto_njl dto=null;
		List<KVDto>vouchers=Lists.newArrayList();
		try {
			dto = orderManager.getPreOrder_njl(proId, infoIds, start, num, voucherId, points);
			String total=getVouchers(voucherId, memberId, NUM.DF_00.parse(dto.getTotal()).doubleValue(), vouchers);
			dto.setTotal(total);
		} catch (ParseException e) {
			logger.error("",e);
		}
		dto.setBookName(name);
		dto.setMobile(mobile);
		model.addAttribute("vouchers", vouchers);
		model.addAttribute("preOrder", dto);
		return new ModelAndView("/order/ConfirmOrder_njl");
	}
	@RequestMapping("/prepareOrder_jd")
	public ModelAndView prepareOrder_jd(
			@RequestParam Long proId,
			@RequestParam (value="infoIds",required=false) List<Long>infoIds,
			@Param("start") String start,
			@Param("num")Integer num,
			@Param("voucherId")Long voucherId,
			@Param("points")Integer points,
			@Param("name")String name,
			@Param("mobile")String mobile,
			@Param("safeEnsure") Integer safeEnsure,
			@Param("cancelEnsure") Integer cancelEnsure,
			@RequestParam (value="memberInfoIds",required=false) List<Long>insurIds,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Long memberId=0l;
		WXPreOrderDto_jd dto=null;
		List<CommonTouristInfoDTO> result=Lists.newArrayList();
		List<KVDto>vouchers=Lists.newArrayList();
		try {
			Double ensureAmount=0d;
			if (null!=safeEnsure&&safeEnsure==1) {
				ensureAmount+=15d;
			}
			if (null!=cancelEnsure&&cancelEnsure==1) {
				ensureAmount+=30d;
			}
			dto = orderManager.getPreOrder_jd(ensureAmount,proId, infoIds, start, num, voucherId, points);
			result=getInfoList(infoIds, result);
			String total=getVouchers(voucherId, memberId, NUM.DF_00.parse(dto.getTotal()).doubleValue(), vouchers);
			dto.setTotal(total);
		} catch (ParseException e) {
			logger.error("",e);
		}
		dto.setBookName(name);
		dto.setMobile(mobile);
		dto.setSafeEnsure(safeEnsure);
		dto.setCancelEnsure(cancelEnsure);
		model.addAttribute("vouchers", vouchers);
		model.addAttribute("list", result);
		model.addAttribute("preOrder", dto);
		return new ModelAndView("/order/ConfirmOrder_jd");
	}
	@RequestMapping("/createOrder_njl")
	public ModelAndView createOrder_njl(
			@RequestParam Long proId,
			@RequestParam ("infoIds") List<Long>infoIds,
			@Param("start") String start,
			@Param("num")Integer num,
			@Param("ticketId")Long ticketId,
			@Param("points")Integer points,

			@Param("name")String name,
			@Param("code")String mobile,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			Member member=WXSession.getMember(request);
//			start=StringUtils.isBlank(start)?DF.FORMAT_YYYY_MM_dd.format(new Date()):start;
//			end=StringUtils.isBlank(end)?DF.FORMAT_YYYY_MM_dd.format(DateUtils.addDay(DF.FORMAT_YYYY_MM_dd.parse(start),1)):end;
//			num=null==num?1:num;
			TicketOrder order=orderManager.createTicketOrder(TicketOrder.type_njl, member);
			order.setType(TicketOrder.type_njl);
			WXToPayDto toPay=orderManager.createTicketItem(proId, member.getId(), order.getId(), num, start, null);
			order.setFee(getFee(ticketId,  toPay.getTotalFee()));
			order.setTotalFee(toPay.getTotalFee()-order.getFee());
			if (null!=points) {
				order.setPoints(points);
				order.setTotalMoney(order.getTotalFee()-points);
			}else {
				order.setTotalMoney(order.getTotalFee());
			}
			order.setSellerName(toPay.getSellerName());
			order.setWithAmount(order.getTotalMoney()-toPay.getScale());
			order.setSellerId(toPay.getSellerId());
			order.setMemberInfos(infoIds);
			order.setName(name);
			order.setMobile(mobile);
			ticketOrderService.update(order);
			model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
			model.addAttribute("orderId", order.getId());
			model.addAttribute("type", "ticket");
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/order/PrePay");
	}
	@RequestMapping("/createOrder_ms")
	public ModelAndView createOrder_ms(
			@RequestParam Long proId,
			@RequestParam ("infoIds") List<Long>infoIds,
			@Param("start") String start,
			@Param("end") String end,
			@Param("num")Integer num,
			@Param("ticketId")Long ticketId,
			@Param("points")Integer points,

			@Param("name")String name,
			@Param("code")String mobile,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			Member member=WXSession.getMember(request);
//			start=StringUtils.isBlank(start)?DF.FORMAT_YYYY_MM_dd.format(new Date()):start;
//			end=StringUtils.isBlank(end)?DF.FORMAT_YYYY_MM_dd.format(DateUtils.addDay(DF.FORMAT_YYYY_MM_dd.parse(start),1)):end;
//			num=null==num?1:num;
			TicketOrder order=orderManager.createTicketOrder(TicketOrder.type_ms, member);
			order.setType(TicketOrder.type_ms);
			WXToPayDto toPay=orderManager.createTicketItem(proId, member.getId(), order.getId(), num, start, end);
			order.setFee(getFee(ticketId,  toPay.getTotalFee()));
			order.setTotalFee(toPay.getTotalFee()-order.getFee());
			if (null!=points) {
				order.setPoints(points);
				order.setTotalMoney(order.getTotalFee()-points);
			}else {
				order.setTotalMoney(order.getTotalFee());
			}
			order.setSellerName(toPay.getSellerName());
			order.setWithAmount(order.getTotalMoney()-toPay.getScale());
			order.setSellerId(toPay.getSellerId());
			order.setMemberInfos(infoIds);
			order.setName(name);
			order.setMobile(mobile);
			ticketOrderService.update(order);
			model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
			model.addAttribute("orderId", order.getId());
			model.addAttribute("type", "ticket");
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/order/PrePay");
	}
	@RequestMapping("/createOrder_jd")
	public ModelAndView createOrder_jd(
			@RequestParam Long proId,
			@RequestParam ("infoIds") List<Long>infoIds,
			@Param("start") String start,
			@Param("num")Integer num,
			@Param("ticketId")Long ticketId,
			@Param("points")Integer points,
			@Param("safeEnsure") Integer safeEnsure,
			@Param("cancelEnsure") Integer cancelEnsure,
			@Param("name")String name,
			@Param("code")String mobile,
			@RequestParam (value="memberInfoIds",required=false) List<Long>insurIds,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			Member member=WXSession.getMember(request);
//			start=StringUtils.isBlank(start)?DF.FORMAT_YYYY_MM_dd.format(new Date()):start;
//			end=StringUtils.isBlank(end)?DF.FORMAT_YYYY_MM_dd.format(DateUtils.addDay(DF.FORMAT_YYYY_MM_dd.parse(start),1)):end;
//			num=null==num?1:num;
			TicketOrder order=orderManager.createTicketOrder(TicketOrder.type_jd, member);
			order.setType(TicketOrder.type_jd);
			WXToPayDto toPay=orderManager.createTicketItem(proId, member.getId(), order.getId(), num, start, null);
			order.setFee(getFee(ticketId,  toPay.getTotalFee()));
			order.setTotalFee(toPay.getTotalFee()-order.getFee());
			if (null!=points) {
				order.setPoints(points);
				order.setTotalMoney(order.getTotalFee()-points);
			}else {
				order.setTotalMoney(order.getTotalFee());
			}
			int ensureAmount=0;
			List<Integer>ensures=Lists.newArrayList();
			if (null!=safeEnsure&&safeEnsure==1) {
				ensureAmount+=1500;
				ensures.add(1);
			}
			if (null!=cancelEnsure&&cancelEnsure==1) {
				ensureAmount+=3000;
				ensures.add(2);
			}
			order.setEnsureAmount(ensureAmount);
			order.setTotalMoney(order.getTotalMoney()+ensureAmount);
			order.setEnsures(ensures);
			order.setSellerName(toPay.getSellerName());
			order.setWithAmount(order.getTotalMoney()-toPay.getScale());
			order.setSellerId(toPay.getSellerId());
			order.setMemberInfos(infoIds);
			order.setName(name);
			order.setMobile(mobile);
			ticketOrderService.update(order);
			model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
			model.addAttribute("orderId", order.getId());
			model.addAttribute("type", "ticket");
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/order/PrePay");
	}
	private int getFee(Long ticketId, Integer total) {
		if (null!=ticketId) {
			VoucherUserMap voucher=voucherService.getById(ticketId);
			if (voucher.getStatus()==0) {
				String now=DF.FORMAT_YYYY_MM_dd.format(new Date());
				if (voucher.getEndDate().compareTo(now) >= 0 && voucher.getStartDate().compareTo(now) <= 0) {
					if (voucher.getAmount()*100 <= total) {
						return voucher.getMoney().intValue()*100;
					}
				}
			}
		}
		return 0;
	}
	@RequestMapping("/createOrder")
	public ModelAndView createOrder(
			@RequestParam List<Long>cartIds,
			@Param("addressId") Long addressId,
			@Param("points")Integer points,
			@Param("ticketId")Long ticketId,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			Member member=WXSession.getMember(request);
			List<Cart>carts=cartService.getByIds(cartIds);
			if (carts.size()<1) {
				response.sendRedirect("/wx/cart/cartIndex");
				return null;
			}
			ReceiveAddress address=addressService.getById(addressId);
			Order order=orderManager.createOrder(address, member.getId());
			WXToPayDto dto=new WXToPayDto();
			for (Cart c : carts) {
				dto.add(orderManager.createItems(c, order.getId(),address.getCityId()));
			}
			order.setFee(getFee(ticketId,  dto.getTotalFee()));
			order.setTotalFee(dto.getTotalFee()-order.getFee());
			order.setExpressFee(dto.getExpressFee());
			if (null!=points) {
				order.setTotalMoney(order.getTotalFee()-points);
			}else {
				order.setTotalMoney(order.getTotalFee());
			}
			order.setTotalMoney(order.getTotalMoney()+order.getExpressFee());
			order.setWithAmount(order.getTotalMoney()-dto.getScale());
			order.setSellerId(carts.get(0).getSellerId());
			order.setCenterId(member.getCenterId());
			orderService.update(order);
			model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
			model.addAttribute("orderId", order.getId());
			model.addAttribute("type", "normal");
			cartService.deleteByIds(cartIds);
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/order/PrePay");
	}
	@RequestMapping("/orderPay")
	public ModelAndView orderPay(
			@RequestParam Long orderId,
			@RequestParam String orderType,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try {
			switch (orderType) {
			case "normal":
				Order order=orderService.getById(orderId);
				model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
				model.addAttribute("orderId", order.getId());
				break;
			case "ticket":
				TicketOrder ticketOrder=ticketOrderService.getById(orderId);
				model.addAttribute("amount", NUM.DF_00.format(ticketOrder.getTotalMoney()/100d));
				model.addAttribute("orderId", ticketOrder.getId());
				break;
			default:
				break;
			}
			model.addAttribute("type", orderType);
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/order/OrderPay");
	}
	@RequestMapping("/orderList")
	public ModelAndView orderList(
			@Param("status") String status,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Long memberId=WXSession.getMember(request).getId();
		Map<String, Object>param=Maps.newHashMap();
		param.put("deleted", false);
		param.put("memberId",memberId);
		param.put("orderByKey", "-ct");
		if (null!=status) {
			switch (status) {
			case "unpay":
				param.put("status",5);
				break;
			case "unreceive":
				param.put("status in",Lists.newArrayList(1,2));
				break;
			case "success":
				param.put("status in",Lists.newArrayList(3));
				break;
			case "other":
				param.put("status in",Lists.newArrayList(4,-1,-2,-3,-4));
				break;
			default:
				break;
			}
			
		}
		List<Order>orders=orderService.list(param);
		model.addAttribute("orders", orders.stream().map(o->{
			return orderManager.getListDto(o);
		}).collect(Collectors.toList()));
		model.addAttribute("status", status);
		return new ModelAndView("/order/OrderList");
	}
	@RequestMapping("/orderDetail")
	public ModelAndView orderDetail(
			@RequestParam Long orderId,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Order order=orderService.getById(orderId);
		model.addAttribute("order", orderManager.getDetailDto(order));
		return new ModelAndView("/order/OrderDetail");
	}
	@RequestMapping("/ticketOrderList")
	public ModelAndView ticketOrderList(
			@Param("status") String status,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		Long memberId=WXSession.getMember(request).getId();
		Map<String, Object>param=Maps.newHashMap();
		param.put("deleted", false);
		param.put("memberId",memberId);
//		param.put("sellerId",sellerId);
		param.put("orderByKey", "-ct");
		if (null!=status) {
			switch (status) {
			case "unpay":
				param.put("status",TicketOrder.status_create);
				break;
			case "unreceive":
				param.put("status",TicketOrder.status_payed);
				break;
			case "success":
				param.put("status",TicketOrder.status_success);
				break;
			case "other":
				param.put("status in",Lists.newArrayList(-1,-2,-3,-4));
				break;
			default:
				break;
			}
			
		}
		List<TicketOrder>orders=ticketOrderService.list(param);
		model.addAttribute("orders", orders.stream().map(o->{
			return orderManager.getTicketListDto(o);
		}).collect(Collectors.toList()));
		model.addAttribute("status", status);
		return new ModelAndView("/order/TicketOrderList");
	}
	@RequestMapping("/ticketOrderDetail")
	public ModelAndView ticketOrderDetail(
			@RequestParam Long orderId,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		TicketOrder order=ticketOrderService.getById(orderId);
		model.addAttribute("order", orderManager.getTicketDetailDto(order));
		return new ModelAndView("/order/TicketOrderDetail");
	}
	@RequestMapping("/toCommentVM")
	public ModelAndView toCommentVM(
			@RequestParam Long orderId,
			@RequestParam String orderType,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		model.addAttribute("orderId", orderId);
		model.addAttribute("orderType", orderType);
		return new ModelAndView("/order/Comment");
	}
	
	@RequestMapping("/comment")
	public void comment(
			@RequestParam Long orderId,
			@RequestParam String orderType,
			@RequestParam Integer score,
			@Param("text")String text,
			@Param(value="images") String images,
			Model model,HttpServletRequest request, HttpServletResponse response) {
		try{
			Long memberId=WXSession.getMember(request).getId();
			Member member = memberService.getById(memberId);
			Comment comment=new Comment();
			comment.setCenterId(member.getCenterId());
			comment.setUserId(memberId);
			comment.setOrderId(orderId);
			comment.setImages(StringUtils.isBlank(images)?null:Lists.newArrayList(images.split(",")).stream().filter(i->StringUtils.isNotBlank(i)).collect(Collectors.toList()));
			comment.setText(StringUtils.isBlank(text)?"":text);
			comment.setNickName(member.getNickname());
			comment.setMemberLogo(member.getLogo());
			comment.setScore(score);
			comment.setCreateTime(new Date());
			if(StringUtils.isNotBlank(orderType)){
				if(orderType.equals("normal")){
					List<OrderItem>items=itemService.findByField("orderId", orderId);
					Order order=orderService.getById(orderId);
					comment.setShopId(order.getSellerId());
					comment.setProIds(items.stream().map(i->{
						return i.getProductId();
					}).collect(Collectors.toList()));
				}else{
					List<TicketOrderItem> ticketItems=ticketOrderItemService.findByField("orderId", orderId);
					TicketOrder ticketOrder=ticketOrderService.getById(orderId);
					comment.setShopId(ticketOrder.getSellerId());
					comment.setProIds(ticketItems.stream().map(i->{
						return i.getProductId();
					}).collect(Collectors.toList()));
				}
			}
			
			commentService.save(comment);
			
			if(StringUtils.isNotBlank(orderType)){
				if(orderType.equals("normal")){
					Order order = orderService.getById(orderId);
					if(order.getStatus()==OrderConstant.WAIT_APPRAISE){
						order.setStatus(OrderConstant.FINISH);
						orderService.update(order);
					}
				}else{
					TicketOrder ticketOrder=ticketOrderService.getById(orderId);
					if(ticketOrder.getStatus()==OrderConstant.WAIT_APPRAISE){
						ticketOrder.setStatus(OrderConstant.FINISH);
						ticketOrderService.update(ticketOrder);
					}
				}
			}
			
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			logger.info("",e);
		}
		
	}
	@RequestMapping("/toChooseAddress")
	public ModelAndView toChooseAddress(
			@Param("oldId")Long oldId,
			@RequestParam String callback,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Long memberId=WXSession.getMember(request).getId();
			 Map<String, Object> param= Maps.newHashMap();
			 param.put("memberId",memberId);
	         param.put("isDeleted in", new Integer[]{0,2});
	         List<ReceiveAddress> addresses = addressService.list(param);
	         List<ReceiveAddressDTO> addressResults = Lists.newArrayList();
	         for (ReceiveAddress address : addresses) {
	        	 ReceiveAddressDTO dto = new ReceiveAddressDTO(address);
	        	 if (oldId!=null&&address.getId()==oldId) {
					dto.setIsChoosen(1);
	        	 }
	             addressResults.add(dto);
	         }
	         model.addAttribute("callback", callback);
	         model.addAttribute("adds", addressResults);
	         return new ModelAndView("/order/AddressManage");
		} catch (Exception e) {
			logger.info("",e);
		}
		return null;
	}
	@RequestMapping("/toChoosePassanger")
	public ModelAndView toChoosePassanger(
			@RequestParam(value="oldId",required=false)List<Long> oldIds,
			@RequestParam String callback,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Long memberId=WXSession.getMember(request).getId();
			 Map<String, Object> param= Maps.newHashMap();
			 param.put("memberId",memberId);
	         param.put("isDeleted in", new Integer[]{0,2});
	         List<CommonTouristInfo> list = infoService.list(param);
	         List<CommonTouristInfoDTO> result = Lists.newArrayList();
	         for (CommonTouristInfo info : list) {
	        	 CommonTouristInfoDTO dto = new CommonTouristInfoDTO(info);
	        	 if (oldIds!=null&&oldIds.contains(info.getId())) {
					dto.setIsChoosen(1);
	        	 }
	        	 result.add(dto);
	         }
	         model.addAttribute("callback", callback);
	         model.addAttribute("list", result);
	         return new ModelAndView("/order/PassangerManage");
		} catch (Exception e) {
			logger.info("",e);
		}
		return null;
	}
	@RequestMapping("/receive")
	public void receive(
			@RequestParam Long orderId,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Long memberId=WXSession.getMember(request).getId();
			Order order=orderService.getById(orderId);
	        if (order.getStatus()==OrderConstant.WAIT_RECEIVE) {
				order.setStatus(OrderConstant.WAIT_APPRAISE);
				orderService.update(order);
				AjaxUtils.renderText(response, "1");
			}
	        AjaxUtils.renderText(response, "0");
		} catch (Exception e) {
			logger.info("",e);
		}
	}
	@RequestMapping("/delete")
	public void delete(
			@RequestParam Long orderId,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Long memberId=WXSession.getMember(request).getId();
			Order order=orderService.getById(orderId);
	        order.setDeleted(true);
	        orderService.update(order);
	        AjaxUtils.renderText(response, "1");
		} catch (Exception e) {
			logger.info("",e);
			AjaxUtils.renderText(response, "0");
		}
	}
	@RequestMapping("/deleteTicket")
	public void deleteTicket(
			@RequestParam Long orderId,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Long memberId=WXSession.getMember(request).getId();
			TicketOrder order=ticketOrderService.getById(orderId);
	        order.setDeleted(true);
	        ticketOrderService.update(order);
	        AjaxUtils.renderText(response, "1");
		} catch (Exception e) {
			logger.info("",e);
			AjaxUtils.renderText(response, "0");
		}
	}
	@RequestMapping("/toRefundVM")
	public ModelAndView toRefundVM(
			@RequestParam Long orderId,
			@RequestParam String orderType,
			@RequestParam Integer type,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			model.addAttribute("type", type);
			model.addAttribute("orderId", orderId);
			model.addAttribute("orderType", orderType);
			switch (orderType) {
			case PRO_ORDER:
				Order order=orderService.getById(orderId);
				model.addAttribute("amount", NUM.DF_00.format(order.getTotalMoney()/100d));
				break;
			case TICKET_ORDER:
				TicketOrder ticket=ticketOrderService.getById(orderId);
				model.addAttribute("amount", NUM.DF_00.format(ticket.getTotalMoney()/100d));
				break;
			default:
				break;
			}
	        return new ModelAndView("/order/Refund");
		} catch (Exception e) {
			logger.info("",e);
			return null;
		}
	}
	@RequestMapping("/refund")
	public void refund(
			@RequestParam Long orderId,
			@RequestParam String orderType,
			@RequestParam Integer type,
			@RequestParam String mobile,
			@RequestParam Integer reason,
			@RequestParam String reasonDetail,
			Model model,
			HttpServletRequest request, 
			HttpServletResponse response
			){
		try {
			Refund refund=new Refund();
			refund.setUserId(WXSession.getMember(request).getId());
			refund.setOrderId(orderId);
			refund.setOrderType(orderType);
			refund.setReason(reason);
			refund.setReasonDetail(reasonDetail);
			refund.setMobile(mobile);
			refund.setType(type);
			refund.setUserName(WXSession.getMember(request).getNickname());
			refund.setCenterId(WXSession.getMember(request).getCenterId());
			switch (orderType) {
			case PRO_ORDER:
				Order order=orderService.getById(orderId);
				refund.setOrderNo(order.getOrderNo());
				refund.setAmount(NUM.DF_00.format(order.getTotalMoney()/100d));
				switch (type) {
				case 1:
					order.setStatus(OrderConstant.BACK);
					break;
				case 2:
					order.setStatus(OrderConstant.BACK_MONEY);
					break;
				default:
					break;
				}
				orderService.update(order);
				break;
			case TICKET_ORDER:
				TicketOrder ticket=ticketOrderService.getById(orderId);
				refund.setOrderNo(ticket.getOrderNo());
				refund.setAmount(NUM.DF_00.format(ticket.getTotalMoney()/100d));
				switch (type) {
				case 1:
					ticket.setStatus(OrderConstant.BACK);
					break;
				case 2:
					ticket.setStatus(OrderConstant.BACK_MONEY);
					break;
				default:
					break;
				}
				ticketOrderService.update(ticket);
				break;
			default:
				break;
			}
			refundService.save(refund);
	        ResponseManager.normalSuccess(response);
		} catch (Exception e) {
			logger.info("",e);
			ResponseManager.SystemError(response);
		}
	}
	
	
	@RequestMapping("/imageUpload")
	public void imageUpload(@RequestParam(value="imgFile", required = false) MultipartFile imgFile,
								HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = commentService.imageUpload(imgFile);
		System.out.println(imgFile);
		AjaxUtils.renderJson(response, map);
	}
}

